<template>
  <div class="myfrom">
    <h1>欢迎来到登录页面</h1>
    <!-- rules 写明验证的信息 -->
    <el-form ref="loginFormRef" :model="loginFrom" :rules="rules"
             label-width="80px">
      <!-- prop 指定验证的规则 -->
      <el-form-item label="用户名" prop="username">
        <el-input prefix-icon="iconfont icon-user"
                  v-model="loginFrom.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input prefix-icon="iconfont icon-lock_fill"
                  v-model="loginFrom.password" type="password" />
      </el-form-item>
      <el-button type="primary" @click="login">登录</el-button>
      <el-button type="default" @click="reset">重置</el-button>
    </el-form>
  </div>
</template>
<script>
export default {
  data () {
    return {
      loginFrom: {
        username: 'admin',
        password: '123456'
      },
      rules: {
        username: [
          { required: true, message: '请输用户名', trigger: 'blur' }
          // { pattern: /^[0-9]*$/, message: "0-9的数字", trigger: "blur" },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
          // { pattern: /^[0-9]*$/, message: "0-9的数字", trigger: "blur" },
        ]
      }
    }
  },
  methods: {
    /* 使用async来精简返回的promise对象 */
    async login () {
      // const result = await this.$axios.post('login', this.loginFrom)
      const { data: { data, meta } } = await this.$axios.post('login', this.loginFrom)
      // console.log(data)
      this.$elmessage({
        message: meta.msg,
        type: meta.status === 200 ? 'success' : 'error'
      })
      window.sessionStorage.setItem('token', data.token)
      this.$router.push('/home')
    },
    reset: function () {
      this.$refs.loginFormRef.resetFields()
    }
  }
}
</script>
<style lang="css" scoped>
.myfrom {
  margin: 100px auto;
  width: 25%;
}
</style>
